package server;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import redstone.xmlrpc.XmlRpcFault;

import com.google.gdata.util.ServiceException;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

import data.Data;


public class Content extends Thread {
	DBObject dbOBJ;
	public Content(DBObject dbOBJ) {
		this.dbOBJ = dbOBJ;
		this.start();
	}

	public void run(){
		try {
			String charset = "UTF-8";
			
			String regtitle = dbOBJ.get("regtitle").toString();
			String regremove = dbOBJ.get("regremove").toString();
			String regcontent = dbOBJ.get("regcontent").toString();
			String typeLink = dbOBJ.get("typeLink").toString();
			String source = dbOBJ.get("source").toString();
			String source_type = dbOBJ.get("source_type").toString();
			String category = dbOBJ.get("category").toString();
			String sumtitlebefore = dbOBJ.get("sumtitlebefore")!=null?dbOBJ.get("sumtitlebefore").toString():"";
			String sumtitleafter = dbOBJ.get("sumtitleafter")!=null?dbOBJ.get("sumtitleafter").toString():"";
			String language = dbOBJ.get("language")!=null?dbOBJ.get("language").toString():"";
			String translate = dbOBJ.get("translate")!=null?dbOBJ.get("translate").toString():"";
			String rewriter_title = dbOBJ.get("rewriter_title")!=null?dbOBJ.get("rewriter_title").toString():"";
			String source_image = dbOBJ.get("source_image")!=null?dbOBJ.get("source_image").toString():"";
			String remove_tag_a = dbOBJ.get("remove_tag_a")!=null?dbOBJ.get("remove_tag_a").toString():"";
			String contain = dbOBJ.get("contain")!=null?dbOBJ.get("contain").toString():"";
			
			ArrayList<String> site = Utils.getStachSite();
			
			Document doc = null;
			
			if(!"yes".equals(translate))
			{
				if(site.contains(Utils.fomatDmain(dbOBJ.get("link").toString())))
				{
					doc = Jsoup.parse(Utils.GetHtml("http://getstackcontent.appspot.com/stack?link="+dbOBJ.get("link").toString(), charset));
				} else {
					doc = Jsoup.parse(Utils.GetHtml(dbOBJ.get("link").toString(), charset));
				}
				
				final int index = doc.select("meta").toString().toLowerCase( ).indexOf( "charset=" );
				if(index != -1)
					charset = doc.select("meta").toString().substring( index+8 ).replaceAll("[^\\\'\\\"0-9a-zA-Z\\-\\_]+[\\w\\W]+", "").replaceAll("[\\\'\\\"]+", "");
				
				
				if(site.contains(Utils.fomatDmain(dbOBJ.get("link").toString())))
				{
					doc = Jsoup.parse(Utils.GetHtml("http://getstackcontent.appspot.com/stack?link="+dbOBJ.get("link").toString(), charset));
				} else {
					doc = Jsoup.parse(Utils.GetHtml(dbOBJ.get("link").toString(), charset));
				}
			} else {
				doc = Utils.Translate(dbOBJ.get("link").toString(), language);
			}
			
			
			String ti = "";
			
			try {
				ti = doc.select(regtitle).text();
			} catch (Exception e) {
				e.printStackTrace();
			}

			doc = Jsoup.parse(doc.select(regcontent).html());
			String[] remove = regremove.split(" ");
			doc.select("script").remove();
			if (remove.length > 0) {
				for (int i = 0; i < remove.length; i++) {
					try {
						if ((remove[i] != null) && (!remove[i].equals("")))
						{
							String[] reg = remove[i].split("\\|"); 
							
							if(reg.length >=2)
							{
								if(reg[1].equals("last"))
								{
									doc.select(reg[0].replaceAll(">", " ")).last().remove();
								} else {
									doc.select(reg[0].replaceAll(">", " ")).first().remove();
								}
							} else {
								doc.select(remove[i].replaceAll(">", " ")).remove();
							}
						}
					} catch (Exception localException1) {
					}
				}
			}
			if(typeLink.equals("nofollow"))
			{
				doc.select("a").attr("rel","nofollow");
			}
			doc.select("a").attr("target","_blank");
			String strContent = changeImg(doc,dbOBJ.get("link").toString(),source_image);

			if(remove_tag_a!=null&&remove_tag_a.equals("yes"))
			{
				strContent = Utils.removeTagA(strContent);
			}
			
			if(source.equals("yes"))
			{
				if(source_type!=null&&source_type.equals("link"))
					strContent += "<br/>Source : <a rel='nofollow' href='"+dbOBJ.get("link").toString()+"' target='_blank'>"+dbOBJ.get("link").toString()+"</a>";
				else
					strContent += "<br/>Source : "+Utils.fomatDmain(dbOBJ.get("link").toString()).replaceAll("[.]{1}", "[dot]");
			}

			String message = doc.text();
			ArrayList<String> term = new ArrayList<String>();
			
			if("yes".equals(rewriter_title))
			{
				ti = Utils.Spin(ti);
			}
			ti = sumtitlebefore+" "+ti+" "+sumtitleafter;
			ti = ti.trim();
			
			int check = 0;
			if(contain!=null&&!contain.equals(""))
			{
				if(!Pattern.matches("^[\\w\\W]*"+contain+"[\\w\\W]*$", ti)){
					check = 1;
				}
			}
			
	        try {
	        	if(ti.length()>10&&strContent.length()>50&&check==0)
	        	{
		        	DBCollection coll = Data.data("blogCraw");
		        	DBObject dbObject = coll.findOne(new BasicDBObject("username",dbOBJ.get("username").toString()).append("blogurl", dbOBJ.get("blogurl").toString()));
	
		        	if(dbObject.get("type").toString().equals("wordpress"))
		        	{
		        		term = Utils.returnTag(message);
		        		PostWp.postWp(ti, Utils.cleanContent(strContent), term,dbObject,category);
		        	}
	
		        	if(dbObject.get("type").toString().equals("blogger"))
		        	{
		        		if(category.equals(""))
		    			{
		    				term = Utils.returnTag(message);
		    			}
		        		PostBlogger.postBlogger(ti, Utils.cleanContent(strContent), term,dbObject,category);
		        	}
		        	if(dbObject.get("type").toString().equals("customurl"))
		        	{
		        		if(category.equals(""))
		    			{
		    				term = Utils.returnTag(message);
		    			}
		        		PostCustomUrl.post(ti, Utils.cleanContent(strContent), term,dbObject,category);
		        	}
	        	}
			} catch (XmlRpcFault e) {
				e.printStackTrace();
			} catch (ServiceException e) {
				e.printStackTrace();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static String changeImg(Document elements,String blogurl,String source_image) throws IOException
	{
		String element = elements.html();
		Elements img = elements.select("img");
		Elements a = elements.select("a");
		element = element.replaceAll("&amp;", "&");
		try {
			for(int i=0;i<a.size();i++)
			{
				String aa= a.eq(i).attr("href");
				if(!"".equals(aa))
				{
					String imageUrl = Utils.fomatLink(aa, blogurl);
					
					element = element.replace(aa, imageUrl);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		try {
			for(int i=0;i<img.size();i++)
			{
				String im= img.eq(i).attr("src");
				if(!"".equals(im))
				{
					String imageUrl = Utils.fomatLink(im, blogurl);
					
					if(source_image!=null&&source_image.equals("cdn"))
					{
						File file = new File(imageUrl);  			
						
	
						String path_image="http://cdn.as7.org/";
						
						String file_name = new Random().nextInt(100)+"_"+file.getName().replaceAll("[?]{1}[\\w\\W]*$", "");
						file_name=file_name.replaceAll("[ ]+", "").replaceAll("%20", "").replaceAll("[^\\w.]+", "");
						
						String destinationFile = path_image+file_name;
						
						element = element.replace(im, destinationFile);
					
						try {
							new Image(imageUrl.replaceAll("[ ]{1}", "%20"), file_name);
						} catch (Exception e) {
							e.printStackTrace();
						}
					} else {
						element = element.replace(im, imageUrl);
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		return element;
	}
	
}
